package com.lych.dubbo.api;

import com.lych.model.mongo.SoulReport;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class SoulReportApiImpl implements SoulReportApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据soulId和type查询报告结果表
     * @param soulId
     * @param type
     * @param userId
     * @return
     */
    @Override
    public List<SoulReport> findBySoulIdWithType(String soulId, String type, Long userId) {
        Query query = Query.query(Criteria.where("soulId").is(soulId).and("type").is(type)
                .and("userId").ne(userId));
        return mongoTemplate.find(query,SoulReport.class);
    }

    /**
     * 保存报告信息
     * @param soulReport
     */
    @Override
    public void save(SoulReport soulReport) {
        //判断是否生成过报告，生成过就删除后再添加
        Query query = Query.query(Criteria.where("userId").is(soulReport.getUserId())
                .and("soulId").is(soulReport.getSoulId()));
        SoulReport report = mongoTemplate.findOne(query, SoulReport.class);
        if (report != null){
            mongoTemplate.remove(report);
        }
        //等待会儿
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        mongoTemplate.insert(soulReport);
    }
}
